package appllo5;

import java.io.*;
import java.net.Socket;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Socket客户端<br>
 */
public class Client1 {

	public static void main(String[] args) throws IOException, InterruptedException {
		// 开启三个客户端，一个线程代表一个客户端
		int i = 0;
		while (true) {
			if (i >= 1) {
				continue;
			} else {
				i++;
			}
//			final String a = String.valueOf(i);
			new Thread(new Runnable() {
				@Override
				public void run() {
					final UUID no = UUID.randomUUID();
					final String imei = no.toString().replace("-", "").substring(17);
					try {
//						@SuppressWarnings("resource") final Socket client = new Socket("127.0.0.1", 8888); // 47.92.165.115
						final Socket client = new Socket("47.92.165.115", 8888); // 47.92.165.115
						// 设置接收数据超时间为10秒
						client.setKeepAlive(true);
						client.setSoTimeout(300 * 1000);

						System.out.println("Cliect[port:" + client.getLocalPort() + "] 与服务端建立连接...");
						final InputStream is = client.getInputStream();
						final Writer writer = new OutputStreamWriter(client.getOutputStream(), "UTF-8");
//						final InputStreamReader input = new InputStreamReader(client.getInputStream(), "UTF-8");
						// InputStream is = client.getInputStream();
						// Reader reader = new InputStreamReader(client.getInputStream(), "UTF-8");

//                        final BufferedReader br = new BufferedReader(
//                                new InputStreamReader(client.getInputStream(), "UTF-8"));
//                        System.out.println(no.toString().replace("-", "").substring(17));
						new Thread(new Runnable() {
							@Override
							public void run() {
								try {
									while (true) {
										writer.write("[f9103f242dcf905faf873c089f74cf7dSR*358954721102107*0002*LK]");
//										writer.write(a);
										writer.flush();// 写完后要记得flush
										System.out.println("Cliect[port:" + client.getLocalPort()
												+ "] 消息发送成功:[14973b1b238d423e88bcd77629dfabaaSR*" + imei + "*0002*LK]");
										Thread.sleep(5000);
									}
								} catch (IOException ex) {
									ex.getStackTrace();
//									Logger.getLogger(Client1.class.getName()).log(Level.SEVERE, null, ex);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).start();
						new Thread(new Runnable() {
							@Override
							public void run() {
								while (true) {
									try {
										byte[] chars = new byte[1024];
										int len = 0;
										if ((len = is.read(chars)) != -1) {
											String c = new String(chars, 0, len);
											System.out.println("收到指令:" + c);
//										String[] carr = c.split(",");
//                                        if (carr.length > 1) {
//                                            String cmd = "[" + carr[0] + "]";
//                                            System.out.println("推送指令:" + cmd);
//                                        }
										}
									} catch (IOException ex) {
										ex.getStackTrace();
//									Logger.getLogger(Client1.class.getName()).log(Level.SEVERE, null, ex);
									}
								}
							}
						}).start();
//                        writer.write("[SR*textimei*0009*LK,0,0,58]");
//                        writer.write("[fcda8bf82b61a56fd581fcd1e7b558d4SFKJ*317006160318431*011c*UD,250818,080158,V,00.000000,N,000.000000,E,0,0,0,0,63,100,1000,50,00000000,1,255,460,0,10170,3673,16,6,johnny008,50:bd:5f:be:62:58,-62,AFOUNDRY-2.4G,70:3a:d8:42:68:88,-90,Kingsman,f0:b4:29:28:98:dd,-90,HT_AP2,f2:b4:29:28:98:dd,-89,1599,a8:57:4e:4f:05:34,-82,902,ec:26:ca:c2:b5:6e,-91][056a073aaa7c8d2ae8ff0f95a1025980SFKJ*317006160318431*000a*LK,0,0,100]");
//                        writer.write("[SR*317000011110003*00011*LK,1,1]");
//                        for (int j = 0; j < 1; j++) {
						// writer.write("317006160318431&&[fcda8bf82b61a56fd581fcd1e7b558d4SFKJ*317006160318431*011c*LED,1,1]");

//                            Thread.sleep(1000);
//                        }
//                        writer.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();

			// new Thread(new Runnable() {
			// @Override
			// public void run() {
			// try {
			//
			// String str;
			// while (true) {
			//// System.out.println(chars);
			// str = br.readLine();
			// if (str == null) {
			// continue;
			// }
			//// if (str.indexOf("eof") > -1) {
			//// break;
			//// }
			// System.out.println("Cliect[port:" + client.getLocalPort() + "] 消息收到了，内容:" +
			// str);
			// }
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			// }
			// }).start();
		}
	}

	/**
	 * 生产测试客户端的工厂
	 */
	static class TestClientFactory {

		public static TestClient createClient() throws Exception {
			return new TestClient("127.0.0.1", 8888);
		}

	}

	/**
	 * 测试客户端
	 */
	static class TestClient {

		/**
		 * 构造函数
		 *
		 * @param host 要连接的服务端IP地址
		 * @param port 要连接的服务端对应的监听端口
		 * @throws Exception
		 */
		public TestClient(String host, int port) throws Exception {
			// 与服务端建立连接
			this.client = new Socket(host, port);
			System.out.println("Cliect[port:" + client.getLocalPort() + "] 与服务端建立连接...");
		}

		private Socket client;

		private Writer writer;

		/**
		 * 发送消息
		 *
		 * @param msg
		 * @throws Exception
		 */
		public void send(String msg) throws Exception {
			// 建立连接后就可以往服务端写数据了
			if (writer == null) {
				writer = new OutputStreamWriter(client.getOutputStream(), "UTF-8");
			}
			writer.write(msg);
			writer.write("eof\n");
			writer.flush();// 写完后要记得flush
			System.out.println("Cliect[port:" + client.getLocalPort() + "] 消息发送成功");
		}

		/**
		 * 接收消息
		 *
		 * @throws Exception
		 */
		public void receive() throws Exception {
			// 写完以后进行读操作
			Reader reader = new InputStreamReader(client.getInputStream(), "UTF-8");
			// 设置接收数据超时间为10秒
			client.setSoTimeout(10 * 1000);
			char[] chars = new char[64];
			int len;
			StringBuilder sb = new StringBuilder();
			while ((len = reader.read(chars)) != -1) {
				sb.append(new String(chars, 0, len));
			}
			System.out.println("Cliect[port:" + client.getLocalPort() + "] 消息收到了，内容:" + sb.toString());
			reader.close();

			// 关闭连接
			// writer.close();
			// client.close();
		}

	}

}
